package com.xfcycle.zebrabikegp.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.xfcycle.zebrabikegp.constant.AlarmConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * 定时器工具类
 * Created by xFcycle on 2017/6/5.
 */

public class AlarmManagerUtil {

    private static List<PendingIntent> pendingIntents = new ArrayList<>();
    private static List<AlarmManager> alarmManagers = new ArrayList<>();

    /**
     * 打开自定义系统计时器
     *
     * @param context      需要传递的上下文
     * @param intentAction 设置的广播频段
     * @param intentExtra  广播携带的标识
     * @param intervalTime 间隔的时间
     */
    public static void startCustomAlarmManager(Context context, String intentAction, String intentExtra, int intervalTime) {
        Intent intent = new Intent(intentAction);
        intent.putExtra(AlarmConstant.INTENT_TAG_KEY, intentExtra);

        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), intervalTime, pi);

        pendingIntents.add(pi);
        alarmManagers.add(am);

    }

    /**
     * 关闭系统计时器
     */
    public static void stopCustomAlarmManager() {
        if (pendingIntents.size() > 0 && alarmManagers.size() > 0 && pendingIntents.size() == alarmManagers.size()) {
            for (int i = 0; i < pendingIntents.size(); i++) {
                alarmManagers.get(i).cancel(pendingIntents.get(i));
            }
        }
    }
}
